package com.lagou.edu.controller;

import com.lagou.edu.entity.Resume;
import com.lagou.edu.service.ResumeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/resume")
public class ResumeController {
    private final ResumeService resumeService;
    @Value("${app.nodeId}")
    private String nodeId;

    public ResumeController(ResumeService resumeService) {
        this.resumeService = resumeService;
    }

    @GetMapping("/list.do")
    public ModelAndView list(HttpServletRequest request, ModelAndView mv) {
        String addr = request.getLocalAddr();
        int port = request.getLocalPort();
        String serverInfo = String.format("%s,%s:%d", nodeId, addr, port);
        final List<Resume> list = resumeService.findAll();
        mv.addObject("list", list);
        mv.addObject("serverInfo", serverInfo);
        mv.setViewName("/resume/list");
//        System.out.println(serverInfo);
        return mv;
    }

    @GetMapping("create.do")
    public ModelAndView create(ModelAndView mv) {
        mv.addObject(new HashMap<>());
        mv.setViewName("/resume/form");
        return mv;
    }

    @PostMapping("create.do")
    public String save(Resume resume) {
        resumeService.save(resume);
        return "redirect:/resume/list.do";
    }

    @GetMapping("{id}.do")
    public ModelAndView edit(@PathVariable Long id, ModelAndView mv) {
        Resume resume = resumeService.findById(id);
        mv.addObject("resume", resume);
        mv.setViewName("/resume/form");
        return mv;
    }

    @PostMapping("{id}.do")
    public String update(@PathVariable Long id, Resume resume) {
        resumeService.save(resume);
        return "redirect:/resume/list.do";
    }

    @GetMapping("/delete/{id}.do")
    public String remove(@PathVariable Long id) {
        resumeService.delete(id);
        return "redirect:/resume/list.do";
    }
}
